<template>
  <view>
    <view class="goods-list">
      <!-- 每一项 -->
      <view v-for="good in goodsList" :key="good.goods_id" @click="goDetails(good.goods_id)">
        <my-goods :good="good"></my-goods>
      </view>
    </view>
  </view>
</template>

<script>
  import {
    escook
  } from '../../utils/escook/index.js'
  import {
    showMsg
  } from '../../utils/interact/index.js'
  export default {
    data() {
      return {
        //请求参数对象
        queryObj: {
          cid: '',
          query: '',
          pagenum: 1,
          pagesize: 10
        },
        goodsList: [],
        total: 0,
        //节流阀
        isLoading: false
      };
    },
    onLoad(options) {
      this.queryObj.query = options.query || '';
      this.queryObj.cid = options.cid || '';

      this.getGoodsListData();
    },

    methods: {
      //网络请求
      async getGoodsListData(cb, showMsg) {
        this.isLoading = true;
        const {
          data: res
        } = await escook.get('api/public/v1/goods/search', this.queryObj);
        this.isLoading = false;
        cb && cb();
        //判断是否请求成功
        if (res.meta.status !== 200) return showMsg();
        showMsg && showMsg('刷新成功');
        this.goodsList = [...this.goodsList, ...res.message.goods];
        this.total = res.message.total;
      },

      //事件回调组
      goDetails(goodsId) {
        uni.navigateTo({
          url: '/subpkg/goods_details/goods_details?goods_id=' + goodsId
        })
      }
    },
    //上拉触底事件的回调
    onReachBottom() {
      //判断是否加载完毕
      if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return showMsg('数据加载完毕');
      //在发起请求获取更多数据之前，进行判断，是否正在请求,如果this.isLoading为true说明请求还未完成，如果用户再次上拉触底再次发起请求会被return出去
      if (this.isLoading) return;
      //页码自增一
      this.queryObj.pagenum++;
      this.getGoodsListData();
    },
    onPullDownRefresh() {
      //重置关键数据
      this.goodsList = [];
      this.queryObj.pagenum = 1;
      this.isLoading = false;
      this.total = 0;

      //发起网络请求获取数据
      this.getGoodsListData(() => uni.stopPullDownRefresh(), showMsg);
    }
  }
</script>

<style lang="scss">

</style>